package com.ug_project.dict.engine.wordtable

import org.junit.Assert.assertEquals
import org.junit.Test
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption

class WordTableTest {
    fun provideWordTable(autoRemove: Boolean = true, action: (table: WordTable) -> Unit) {
        val wordTableFile = Paths.get("temp_wordtable.wdt")
        if (autoRemove) Files.deleteIfExists(wordTableFile)
        if (Files.notExists(wordTableFile)) Files.createFile(wordTableFile)
        val channel = FileChannel.open(wordTableFile, StandardOpenOption.READ, StandardOpenOption.WRITE)
        val table = WordTable(channel)
        action(table)
        channel.close()
    }

    @Test
    fun readWrite() {
        provideWordTable { table ->
            val unicode_a = 'a'.toInt()
            val unicode_b = 'b'.toInt()

            table[unicode_a] = WordRow(table, 0).apply {
                unicode = unicode_a
                add(222, 1)
                add(555, 4)
            }
            assertEquals(5, table[unicode_a]!!.layerCount)

            table[unicode_b] = WordRow(table, table[unicode_a]!!.size).apply {
                unicode = unicode_b
                add(111, 0)
                add(444, 3)
            }

            table.write()

            assertEquals(5, table[unicode_a]!!.layerCount)

            assertEquals(111, table[unicode_b]!!.pointers[0])
            assertEquals(444, table[unicode_b]!!.pointers[3])

            assertEquals(222, table[unicode_a]!!.pointers[1])
            assertEquals(555, table[unicode_a]!!.pointers[4])



            provideWordTable(false){tableLoaded ->
                assertEquals(unicode_a, tableLoaded[unicode_a]!!.unicode)
                assertEquals(unicode_b, tableLoaded[unicode_b]!!.unicode)

                assertEquals(5, tableLoaded[unicode_a]!!.layerCount)
                assertEquals(4, tableLoaded[unicode_b]!!.layerCount)



                assertEquals(222, tableLoaded[unicode_a]!!.pointers[1])
                assertEquals(555, tableLoaded[unicode_a]!!.pointers[4])

                assertEquals(0, tableLoaded[unicode_a]!!.pointers[0])
                assertEquals(0, tableLoaded[unicode_a]!!.pointers[2])
                assertEquals(0, tableLoaded[unicode_a]!!.pointers[3])



                assertEquals(111, tableLoaded[unicode_b]!!.pointers[0])
                assertEquals(444, tableLoaded[unicode_b]!!.pointers[3])

                assertEquals(0, tableLoaded[unicode_b]!!.pointers[1])
                assertEquals(0, tableLoaded[unicode_b]!!.pointers[2])

                assertEquals(table[unicode_a]!!.pointers.size, tableLoaded[unicode_a]!!.pointers.size)

            }
        }
    }
}
